﻿using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Modules.Person.Repositories;
using PmSoft;
using PmSoft.ApplicationContext;
using PmSoft.Exceptions;
using PmSoft.Utilities;
using System.Drawing.Printing;
using static Modules.Person.PersonConstants;

namespace Modules.Person
{
    /// <summary>
    /// 人员企业合同service
    /// </summary>
    [UseDI(ServiceLifetime.Scoped)]
    public class PersonCorpContractService
    {
        private readonly PersonCorpContractRepository personCorpContractRepository;
        private readonly IApplicationContext applicationContext;
        private readonly PersonAttachmentService personAttachmentService;
        private readonly PersonService personService;
        private readonly ILogger logger;

        public PersonCorpContractService(PersonCorpContractRepository personCorpContractRepository,
            IApplicationContext applicationContext,
            PersonService personService,
            PersonAttachmentService personAttachmentService, ILogger<PersonCorpContractService> logger)
        {
            this.personCorpContractRepository = personCorpContractRepository;
            this.applicationContext = applicationContext;
            this.personAttachmentService = personAttachmentService;
            this.personService = personService;
            this.logger = logger;
        }

        public void Create(PersonCorpContract entity, IEnumerable<string> attachments)
        {
            if (personCorpContractRepository.ExistByProjectIdPersonIdCorpId(entity.PersonId, entity.ProjectId, entity.CorpId)) throw new BusinessException("该人员已存在合同,无法新增");
            try
            {
                applicationContext.Transaction.Begin();//开始事务
                entity.CreateDate = DateTime.Now;
                personCorpContractRepository.Insert(entity);

                #region 附件

                var personAttachments = personAttachmentService.GetPersonAttachmentByObjectIdAndType(entity.Id, 人员附件类型.合同附件, 人员附件租户.Contract).Select(a => a.Id);
                personAttachmentService.Deleted(personAttachments);

                foreach (var item in attachments)
                {
                    PersonAttachment projectAttachment = new()
                    {
                        Id = Guid.NewGuid().ToString().Replace("-", ""),
                        AttachmentId = item,
                        ObjectId = entity.Id,
                        AttachmentType = 人员附件类型.合同附件,
                        CreateTime = DateTime.Now,
                        Tenant = 人员附件租户.Contract
                    };
                    personAttachmentService.Create(projectAttachment);
                }

                #endregion 附件

                applicationContext.Transaction.Complete();//完成事务
            }
            catch (Exception ex)
            {
                applicationContext.Transaction.Abort();//回滚事务
                logger.LogError(ex, $"CreateContract Exception cardno:{entity.Code}");
                throw new BusinessException("写入合同数据失败");
            }
        }

        public void Update(PersonCorpContract entity, IEnumerable<string> attachments)
        {
            try
            {
                applicationContext.Transaction.Begin();//开始事务
                personCorpContractRepository.Update(entity);

                #region 附件

                var personAttachments = personAttachmentService.GetPersonAttachmentByObjectIdAndType(entity.Id, 人员附件类型.合同附件, 人员附件租户.Contract).Select(a => a.Id);
                personAttachmentService.Deleted(personAttachments);

                foreach (var item in attachments)
                {
                    PersonAttachment projectAttachment = new()
                    {
                        Id = Guid.NewGuid().ToString().Replace("-", ""),
                        AttachmentId = item,
                        ObjectId = entity.Id,
                        AttachmentType = 人员附件类型.合同附件,
                        CreateTime = DateTime.Now,
                        Tenant = 人员附件租户.Contract
                    };
                    personAttachmentService.Create(projectAttachment);
                }

                #endregion 附件

                applicationContext.Transaction.Complete();//完成事务
            }
            catch (Exception ex)
            {
                applicationContext.Transaction.Abort();//回滚事务
                logger.LogError(ex, $"CreateContract Exception cardno:{entity.Code}");
                throw new BusinessException("写入合同数据失败");
            }
        }

        public void Delete(int id)
        {
            personCorpContractRepository.DeleteByEntityId(id);
        }

        public void Deleted(IEnumerable<int> ids)
        {
            foreach (var id in ids)
            {
                Delete(id);
            }
        }

        public IPagedList<PersonCorpContract> GetPersonCorpContracts(PersonCorpContractQuery query, int pageIndex, int pageSize)
        {
            return personCorpContractRepository.GetPersonCorpContracts(query, pageIndex, pageSize);
        }

        public IEnumerable<PersonCorpContract> GetPersonCorpContractByIdsProjectId(IEnumerable<int> ids, int projectId)
        {
            return personCorpContractRepository.GetPersonCorpContractByIdsProjectId(ids, projectId);
        }

        public IEnumerable<PersonCorpContract> GetPersonCorpContractsByPersonIds(IEnumerable<int> personIds)
        {
            return personCorpContractRepository.GetPersonCorpContractsByPersonIds(personIds);
        }

        public PersonCorpContract? GetPersonCorpContract(int id)
        {
            return personCorpContractRepository.Get(id);
        }

        public IEnumerable<PersonCorpContract> GetPersonCorpContractsByProjectIds(IEnumerable<int> projectIds)
        {
            return personCorpContractRepository.GetPersonCorpContractsByProjectIds(projectIds);
        }

        public PersonCorpContract? GetPersonCorpContractsByProjectIdAndCorpIdPersonId(int projectId, int corpId, int personId)
        {
            IEnumerable<PersonCorpContract> personConstants = personCorpContractRepository.GetPersonCorpContractsByProjectIds(ValueUtility.ConvertToList<int>(projectId.ToString()));
            return personConstants.OrderByDescending(a => a.EndDate).FirstOrDefault(a => a.CorpId == corpId && a.PersonId == personId);
        }

        public IEnumerable<PersonCorpContract> GetPersonCorpContractssByProjectIdAndCorpIdPersonId(int projectId, int corpId, int personId)
        {
            IEnumerable<PersonCorpContract> personConstants = personCorpContractRepository.GetPersonCorpContractsByProjectIds(ValueUtility.ConvertToList<int>(projectId.ToString()));
            return personConstants.Where(a => a.CorpId == corpId && a.PersonId == personId);
        }

        public IEnumerable<PersonCorpContract> GetPersonCorpContractssByProjectIdAndPersonId(int projectId, int personId)
        {
            IEnumerable<PersonCorpContract> personConstants = personCorpContractRepository.GetPersonCorpContractsByProjectIds(ValueUtility.ConvertToList<int>(projectId.ToString()));
            return personConstants.Where(a => a.PersonId == personId);
        }
    }
}